import express, { Application, Request, Response } from 'express';
import bodyParser from 'body-parser';
import { routes, users, IRoute, IUser } from './data';

const app: Application = express();
const PORT: number = 8081;

interface IBody {
  uid: number;
}

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

//接收前端uid判断权限
app.post('/user_router_list', (req: Request, res: Response) => {
  const { uid }: IBody = req.body;
  if (uid) {
    //获取用户信息
    const userInfo: IUser | undefined = users.find((user) => user.id == uid);

    //数组容器保存权限列表数据
    const authRouteList: IRoute[] = [];

    //找到用户信息时
    if (userInfo) {
      //获取用户权限信息
      userInfo.auth.map((rid) => {
        routes.map((route: IRoute) => {
          if (route.id === rid) {
            authRouteList.push(route);
          }
        });
      });

      //响应权限列表数据
      res.status(200).send({
        code: 0,
        msg: 'ok.',
        data: authRouteList
      });
    } else {
      //找不到用户信息时
      res.status(200).send({
        code: 1001,
        msg: 'No userInfo for this uid.',
        data: null
      });
    }
  } else {
    //找不到用户时
    res.status(200).send({
      code: 1002,
      msg: 'No uid received.',
      data: null
    });
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on ${PORT}.`);
});
